﻿/** 
 * Project Name:jdplat 
 * File Name:ShiroRealm1.java 
 * Package Name:com.jdplat.jdm.web.shiro 
 * Date:2016年12月8日上午10:42:07 
 * Copyright (c) 2016, 948434963@qq.com All Rights Reserved. 
 * 
*/  
  
package com.jdplat.jdm.web.shiro;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jdplat.jdm.web.entity.User;
import com.jdplat.jdm.web.service.system.ISystemPermissionService;
import com.jdplat.jdm.web.service.system.ISystemRoleService;
import com.jdplat.jdm.web.service.system.ISystemUserService;

/** 
 * ClassName:ShiroRealm <br/> 
 * Function: TODO ADD FUNCTION. <br/> 
 * Reason:   TODO ADD REASON. <br/> 
 * Date:     2016年12月8日 上午10:42:07 <br/> 
 * @author   qirp
 * @version   
 * @since    JDK 1.7 
 * @see       
 */
@Service
public class ShiroRealm extends AuthorizingRealm{
	
	@Autowired
	private ISystemUserService userService;
	@Autowired
	private ISystemRoleService roleService;
	@Autowired
	private ISystemPermissionService permissionService;

	/**
	 * 授权
	 * Authorization has three core elements that we reference quite a bit in Shiro– permissions, roles, and users.
	 * 
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//当前用户的登录名（凭证）
		String currentUserName = (String)super.getAvailablePrincipal(principals);
		List<String> roleList = new ArrayList<String>();//角色
		List<String> permissionList = new ArrayList<String>();//权限
		//获取用户信息
		User user = userService.getUserInfo(currentUserName);
		if (null != user) {
			List<Map<String, Object>> roles = roleService.getUserRoles(user.getId().toString());
			// 实体类User中包含有用户角色的实体类信息
			if (null != roles && roles.size() > 0) {
				// 获取当前登录用户的角色
				for (Map<String, Object> role : roles) {
					roleList.add(role.get("NAME") + "");
					// 实体类Role中包含有角色权限的实体类信息
					List<Map<String, Object>> permission = permissionService.getUserPermission(role.get("ID").toString());
					if (null != permission && permission.size() > 0) {
						// 获取权限
						for (Map<String, Object> pmss : permission) {
							if (!StringUtils.isEmpty(pmss.get("PERM_CODE") + "")) {
								permissionList.add(pmss.get("PERM_CODE") + "");
							}
						}
					}
				}
			}
		}
		//给当前用户设置角色和权限
		SimpleAuthorizationInfo simpleAuthInfo = new SimpleAuthorizationInfo();
		simpleAuthInfo.addRoles(roleList);
		simpleAuthInfo.addStringPermissions(permissionList);
		return simpleAuthInfo;
	}

	/**
	 * 认证
     *1、Collect the subject’s principals and credentials
     *2、Submit the principals and credentials to an authentication system.
     *3、Allow access, retry authentication, or block access
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;//1
		if(token.getPassword().toString() != null && token.getUsername() != null){
			if(userService.checkLogin(token)){
				AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), this.getName());//2
				User user = userService.getUserInfo(token.getUsername());
				this.setSession("user", user);
				return authcInfo;
			}
		}
		return null;
	}
	
	
	private void setSession(Object key,Object value){
		Subject currentUser = SecurityUtils.getSubject();
		if(null != currentUser){
			Session session = currentUser.getSession();
			if(null != session){
				session.setAttribute(key, value);
			}
		}
	}

}
 